package com.hspedu.sqlsession;

import com.hspedu.config.Function;
import com.hspedu.config.MapperBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

public class HspMapperProxy implements InvocationHandler {
    private HspSqlSession hspSqlSession;
    private String mapperFile;
    private HspConfiguration hspConfiguration;

    public HspMapperProxy(HspConfiguration hspConfiguration,HspSqlSession hspSqlSession,Class clazz){
        this.hspConfiguration = hspConfiguration;
        this.hspSqlSession = hspSqlSession;
        this.mapperFile = clazz.getSimpleName() + ".xml";
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MapperBean readMapper = hspConfiguration.readMapper(this.mapperFile);
        if(!method.getDeclaringClass().getName().equals(readMapper.getInterfaceName())){
            return null;
        }
        List<Function> list = readMapper.getList();
        if (null != list && 0 != list.size()){
            for(Function function:list){
                if(method.getName().equals(function.getFuncName())){
                    //在 Java 中，String.valueOf() 是一个静态方法，它用于将不同类型的值转换为 String。它常用于将基本数据类型、对象或 char 数组转换为字符串。
                    return hspSqlSession.selectOne(function.getSql(),String.valueOf(args[0]));
                }
            }
        }
        return null;

    }
}
